/**
 * APP全局变量、方法
 * by zhujj 20170826
 */

/*系统常量*/
SYS_PARAM = {
	/** 站点信息集合 */
	KEY_SITES_LIST:'$KEY_SITES_LIST',
	/** 登录信息索引 */
	KEY_LOGIN_INFO:'$LOGIN_INFO',
	/** 是否第一次打开app */
	KEY_LAUCH_FLAG:'$LAUCH_FLAG',
	/** 全站检索关键字 */
	KEY_KWS:'$KEY_KWS',
	/** 当前选择的区划 */
	KEY_CUR_DISTRICT:'KEY_CUR_DISTRICT',
	/** 当前选择的站点*/
	KEY_CUR_SITE:'KEY_CUR_SITE',
	/** 当前办事指南选择的区划 */
	KEY_BSZN_DISTRICT:'KEY_BSZN_DISTRICT',
	/** 当前办事指南选择的区划ID */
	KEY_BSZN_DISTRICT_ID:'KEY_BSZN_DISTRICT_ID',
	/** 热门搜索 */
	KEY_HOT_SEARCHING:'KEY_HOT_SEARCHING',
	/**	 登录页面id */
	KEY_LOGIN_VIEW_ID:'KEY_LOGIN_VIEW_ID',
	/** 事项预约短信模板  */
	SEND_SERVICE_BOOKING_SMS:'SEND_SERVICE_BOOKING_SMS',
	/** 事项预约提醒短信模板*/
	SEND_REMIND_BOOKING_SMS:'SEND_REMIND_BOOKING_SMS',
	/** 通用短信验证码模板*/
	SEND_ID_CODE_SMS:'SEND_ID_CODE_SMS',
	/** 咨询投诉模板*/
	SEND_ADVICE_CODE_SMS:'SEND_ADVICE_CODE_SMS',
	/** 通用邮箱验证码模板*/
	SEND_ID_CODE_MAIL:'SEND_ID_CODE_MAIL',
	/** 当前操作系统信息 */
	KEY_SYS_INFO:'KEY_SYS_INFO',
	/**便民服务开通城市*/
	BM_CITY:'合肥'
}

/*加载H5插件完成后的事件*/
document.addEventListener("plusready", function() {
	//仅支持竖屏显示
	plus.screen.lockOrientation("portrait-primary");
	var wv = plus.webview.currentWebview();
	if(wv.backfun == true){//重写关闭方法
		mui.back = function(){
			plus.webview.currentWebview().close('zoom-fade-in',mui.os.android ? 200 : 300);
		}
	}
	//隐藏滚动条
	wv.setStyle({
		scrollIndicator: 'none'
	});
	utils.netchangeListener();
}, false);

/**
 *获取当前选择的地区 
 */
function getCurrentDistrict(){
	//{id:'',name:''}
	var d = localStorage.getItem(SYS_PARAM.KEY_CUR_DISTRICT);
	if(!d)return null;
	return JSON.parse(d);
}

/**
 *获取当前选择的地区 id
 */
function getCurrentDistrictId(){
	var d = getCurrentDistrict();
	if(d){
		return d.id;
	}
	return '00000000000000000000000000000000';//默认安徽省区划id
}

/**
 *获取当前选择的站点 
 */
function getCurrentSite(){
	//{id:'',name:''}
	var s = localStorage.getItem(SYS_PARAM.KEY_CUR_SITE);
	if(!s)return null;
	return JSON.parse(s);;
}

/**
 *获取当前选择的站点id
 */
function getCurrentSiteId(){
	var s = getCurrentSite();
	if(s){
		return s.id;
	}
	return '1';//默认站点安徽省
}

/**
 *首页图片新闻-移动app 图片新闻栏目主键
 */
function getSlideColumnId(){
	return '402881b95d40441e015d4085f4020000';
}


/**
 * 获得用户
 */
function getUser(){
	return localStorage.getItem(SYS_PARAM.KEY_LOGIN_INFO)?JSON.parse(localStorage.getItem(SYS_PARAM.KEY_LOGIN_INFO)):null;
}

/*检查是否登录*/
function isLogin() {
	var s = localStorage.getItem(SYS_PARAM.KEY_LOGIN_INFO);
	if(s && JSON.parse(s).userId) {
		return true;
	} 
	return false;
}

/*获取用户名*/
function getLoginUserCode() {
	var s = localStorage.getItem(SYS_PARAM.KEY_LOGIN_INFO);
	if(s && JSON.parse(s).account) {
		return JSON.parse(s).account;
	} else {
		return null;
	}
}

//验证是否实名
function isAttest(needtaost){
	//未登录跳转到登录页
	var user = getUser();
	if(!user || !user.account){
		if(needtaost){
			mui.toast('请先登录！');
		}
		return false;
	}else{//提醒需要实名
		if(!user.hasAttest ||  user.hasAttest!= '1'){
			if(needtaost){
				mui.toast('您可以在电脑上实名认证！');
			}
			return false;
		}else{
			return true;
		}
	}
}

/**
 * 获得用户id
 */
function getUserId(){
	var user = getUser()
	if(user){
		return user.userId;
	}else{
		return null;
	}
}

/**
 * wangsh
 * @param {Object} type 类型 
 */
function encodeParam(paramJson){
	var param = '';
	//加密信息,一般情况下的顺序为 flg userid .....
	var flg = '';
	for(var pj in paramJson){
		var _value = paramJson[pj];
		if(_value!=null && _value != '' ){
			flg += md5(_value);
			if(pj == 'token' ) {continue};
			param += ('&'+pj+'='+_value);
		}
	}
	param += '&token='+md5(flg);
	return param.substr(1);
}


/**
 * 跳转登录界面 
 * isJump - 登录成功后是否执行页面跳转 true-跳转，false-直接关闭当前页面
 */
function showLogin(isJump) {
	if(!window.plus) return;
	if(isLogin()){
		mui.toast('您已是登录状态！');
		return;
	}
	var wv_id = SYS_PARAM.KEY_LOGIN_VIEW_ID;
	var href = '_www/src/login/login.html';
	var aniShow = 'slide-in-right';
	if(typeof isJump == 'undefined'){
		isJump = true;
	} 
	var wv = plus.webview.getWebviewById(wv_id);
	if(!wv){
		wv = mui.preload({
			url: href,
			id: wv_id,
			styles: {
				popGesture: "hide",
				top: 0,
				bottom: 0
			},
			extras: {
				isJump:isJump
			}
		});
	}

	wv.show('slide-in-right',200);
}

/**
 * 扫描处理
 */
function scanHander(t, r, f) {
	if(r && r.indexOf('scanlogin') >= 0) {
		if(!isLogin()) {
			var btnArray = ['取消', '登录'];
			mui.confirm('您尚未登录，去登录？', '提示', btnArray, function(e) {
				if(e.index == 1) {
					showLogin();
				} else {

				}
			});
		} else {
			var code = r.split(':')[1];
			plus.nativeUI.showWaiting();
			utils.ajax('appHttpService/updateQRCode.do', function(data) {
				data = eval("(" + data + ")");
				if (data.code == 0 || data.code == '0' ) {
					mui.toast('扫描成功！');
				}else{
					mui.toast(data.result);
				}
				plus.nativeUI.closeWaiting();
				//mui.toast('扫描成功！');
			}, 'code=' + code + '&userCode=' + getLoginUserCode(),null,function(){
				plus.nativeUI.closeWaiting()
			});
		}
	} else if(r && (r.indexOf('http://') == 0 || r.indexOf('https://') == 0)) {
		var btnArray = ['取消', '打开'];
		mui.confirm('是否用手机浏览器打开扫描到的网页？', '提示', btnArray, function(e) {
			if(e.index == 1) {
				plus.runtime.openURL(r, function() {
					mui.toast('打开网页失败！');
				});
			} else {

			}
		});
	} else if(r && r.length ==32 ){
		utils.showWaiting();
    	var hsw = openNewWin('_www/src/work/bszn_info.html?serviceOid=' + r,null, 'bszn_info');
    	//mui.fire(hsw,'getDetail',{serviceOid:r});
	} else {
		//根据办件编号查询办件信息
		var ajaxUrl = 'appHttpService/checkZwfwCaseByCaseNum.do';
		var config = {
//			'host':BASE_PARAM.KEY_GGFW_HOST,
			'method': 'get',
			'showWait': true
//			'timeout': 1000,
//			'headers': {
//				'Content-Type': 'application/json'
//			}
		};
		var param = 'caseNum='+ r.split("&")[0]
		//console.log(r);
		//console.log(param);
		utils.ajax(ajaxUrl,function(data){
			regInfo = data;
			casedata = JSON.parse(data);
//			if(data.state == 0 || data.state == '0'){
//				mui.toast('未查询到该办件信息');
//			}
			data = JSON.parse(data);
			if(data.code == '2'){
				utils.showWaiting();
				openNewWin('_www/src/work/bjjdcx_info.html?caseNum=' + data.result);
				return;
			}else{
				mui.toast('办件信息不存在');
				return;
			}
		},param,function(){
			mui.toast('信息查询失败');
		});
	}
}

/**
 * 跳转二维码扫描结果成功授权页面
 */
function scanLoginResult() {
	if(!window.plus) return;
	var id = 'barcode_scan_result';
	var href = '_www/src/global/barcode_scan_result.html';
	var aniShow = 'pop-in';

	mui.preload({
		url: href,
		id: id,
		styles: {
			popGesture: "hide",
			top: 0,
			bottom: 0
		},
		extras: {

		}
	});

	//默认跳转到app首页
	localStorage.setItem('index', 'index.html');

	mui.openWindow({
		id: id,
		show: {
			aniShow: aniShow
		},
		waiting: {
			autoShow: false
		}
	});
}

/**
 * 文字分享
 * @param {Object} shareTip-分享标题
 * @param {Object} shareText-分享内容
 */
function share(shareTip, shareText) {
	if(utils)utils.showWaiting();
	//导入Java类对象
	var Context = plus.android.importClass("android.content.Intent");
	//获取应用主Activity
	var Main = plus.android.runtimeMainActivity();
	//将类Context的这个行为(Action)ACTION_SEND，赋给shareIntent
	var shareIntent = new Context(Context.ACTION_SEND);
	//***以下两种写法是一样的
	//plus.android.invoke(shareIntent,"setType","text/plain");
	//plus.android.invoke(shareIntent,"putExtra",Context.EXTRA_TEXT,shareText);
	//设置分享类型
	shareIntent.setType("text/plain");
	//设置分享文本
	shareIntent.putExtra(Context.EXTRA_TEXT, shareText);
	//***以上两种写法是一样的
	//指定分享的包名
	//shareIntent.setPackage('com.tencent.mm',);
	Main.startActivity(Context.createChooser(shareIntent, shareTip));
	if(utils)utils.closeWaiting();
}

/**
 * 打开新窗口 (可配置硬件加速)
 * @param {URIString} url : 要打开页面url(无需_www/html)
 * @param {boolean} wa : 是否显示等待框
 * @param {boolean} ns : 是否不自动显示
 * @param {JSON} ws : Webview窗口属性
 * @param {JSON} extras : Webview参数
 */
var openw;
function openNew (url, id ,extras, wa, ns, ws) {
	if(openw) { //避免多次打开同一个页面
		return null;
	}
	if(window.plus) {
		wa && (utils.showWaiting());
		ws = ws || {};
		ws.scrollIndicator || (ws.scrollIndicator = 'none');
		ws.scalable || (ws.scalable = false);
		ws.hardwareAccelerated||(ws.hardwareAccelerated = false);//true 开启印鉴加速
		openw = plus.webview.create(url, id, ws, extras);
		ns || openw.addEventListener('loaded', function() { //页面加载完成后才显示
			setTimeout(function() { //延后显示可避免低端机上动画时白屏
				openw.show('slide-in-right');
				utils.closeWaiting();
			}, 100);
		}, false);
		plus.key.addEventListener('backbutton', function() {
			mui.back();
		}, false);
		openw.addEventListener('close', function() { //页面关闭后可再次打开
			openw = null;
		}, false);
		return openw;
	} else {
		w.open(url);
	}
	return null;
}

/**
 * 打开新窗口
 * url-要打开的页面地址
 * config_-Webview窗口对象的样式
 * winid-相同的winid，可实现页面复用
 * params-给新页面传递参数
 * isClose-打开新页面是否关闭当前页面
 */
var _oldViewTime = null;
function openNewWin(url, config_, winid,params,isClose) {
	var d = new Date();
	
	if(_oldViewTime &&  (d.getTime() - _oldViewTime < 1000)  ){
		return null;
	}
	_oldViewTime = d.getTime();
	
	var config = 
		{
			top: '0px', //新页面顶部位置
			bottom: '0px', //新页面底部位置
			scrollIndicator:"none",//隐藏滚动条
			bounce:'vertical',
			bounceBackground:'#ccc',
			render:'always',
			popGesture:'none'
		}
	
	mui.extend(true,config,config_);
	
	//跳转界面后是否关闭当前页面
	if(isClose){
		var curWin = plus.webview.currentWebview();
		setTimeout(function() {
			curWin.hide(); //避免出现关闭动画
			curWin.close();
		}, 420);
	}
	
	var win = plus.webview.getWebviewById(winid);
	
	if (win){
		
	}else{
		params = params ? params : {};
		mui.extend(true,params,{backfun:true});
		//http://www.html5plus.org/doc/zh_cn/webview.html#plus.webview.create
		win = plus.webview.create(url, winid ? winid : url, config, params);
	}
	return win;
}

//--------创建页面模板-----------------
var aniShow = "pop-in";
var templates = {};
var getTemplate = function(name, header, content) {
	var template = templates[name];
	if(!template) {
		//预加载共用父模板；
		var headerWebview = mui.preload({
			url: header,
			id: name + "-main",
			styles: {
				popGesture: "hide"
			},
			extras: {
				mType: 'main'
			}
		});
		//预加载共用子webview
		var subWebview = mui.preload({
			url: !content ? "" : content,
			id: name + "-sub",
			styles: {
				top: window.immersed ? immersed + 44 + 'px' : '44px',
				bottom: '0px',
				render:'always',
				bounce:'vertical'
			},
			extras: {
				mType: 'sub'
			}
		});

		if(mui.os.android && parseFloat(mui.os.version) >= 4.4) {
			subWebview.hide();
		}
		
		headerWebview.append(subWebview);
		templates[name] = template = {
			name: name,
			header: headerWebview,
			content: subWebview,
		};
	}
	return template;
};

var initTemplates = function(tempName) {
	getTemplate(tempName, '../global/template.html');
};

var oldViewId = null;
var oldViewTime = null;
var showTemplates_old = function(tempName, title, href, aniShow) {
	var d = new Date();
	if(oldViewId && oldViewId == tempName){
		if(oldViewTime &&  (d.getTime() - oldViewTime <1000)  ){
			return null;
		}
	}
	
	oldViewId = tempName;
	oldViewTime = d.getTime();
	
	if(!aniShow) aniShow = 'slide-in-right';

	//使用父子模板方案打开的页面
	//获得共用模板组
	var template = getTemplate(tempName, '_www/src/global/template.html');
	//获得共用父模板
	var headerWebview = template.header;
	//获得共用子webview
	var contentWebview = template.content;

	//通知模板修改标题；
	if(plus.os.name != 'Android'){//ios
		headerWebview.onloaded = function() {
			headerWebview.evalJS('updateHeader("'+title+'","'+href+'");');
		}
	}else{//android
		headerWebview.evalJS('updateHeader("'+title+'","'+href+'");');
		setTimeout(function(){//修复未知bug
			if(!headerWebview.isVisible()){
				if(templates[tempName].header)templates[tempName].header.close();
				if(templates[tempName].content)templates[tempName].content.close();
				templates[tempName] = null;
				oldViewTime = null;
				showTemplates(tempName, title, href, aniShow);
				//console.log(tempName + '-->' + title + '-->' + href);
			}
		},500);
	}
	
	if(mui.os.ios || (mui.os.android && parseFloat(mui.os.version) < 4.4)) {
		var reload = true;
		if(contentWebview.getURL() != href) {
			contentWebview.loadURL(href);
		} else {
			reload = false;
		}
		headerWebview.show(aniShow, mui.os.android ? 200 : 300);
		if(reload)headerWebview.evalJS('updateHeader("'+title+'","'+href+'");');
		setTimeout(function(){//修复未知bug
			if(!headerWebview.isVisible()){
				if(templates[tempName].header)templates[tempName].header.close();
				if(templates[tempName].content)templates[tempName].content.close();
				templates[tempName] = null;
				oldViewTime = null;
				showTemplates(tempName, title, href, aniShow);
				//console.log(tempName + '-->' + title + '-->' + href);
			}
		},500);
	}
}
//--------

var oldViewId = null;
var oldViewTime = null;
var showTemplates = function(id, title, href,extras,_styles) {
	var d = new Date();
	if(oldViewId && oldViewId == id){
		if(oldViewTime &&  (d.getTime() - oldViewTime <1000)  ){
			return null;
		}
	}
	
	oldViewId = id;
	oldViewTime = d.getTime();
	
	var styles = {
		bottom: '0px',
		render:'always',
		bounce:'vertical',
		bounceBackground:'#000000',
		replacewebapi:{geolocation:'auto'},
//		backButtonAutoControl:"close",
		softinputMode:'adjustResize',
		titleNView:{
			autoBackButton:true,
			backgroundColor:'#0B7EFD',
			titleColor:'#fff',
			titleText:title,
			type:"default"
		}
	};
	_styles = _styles ? _styles : {};
	mui.extend(true,styles,_styles);
	extras = extras ? extras : {};
	mui.extend(true,extras,{backfun:true});//重写返回方法，见上方plusready方法
	var wv = plus.webview.create( href, id, styles, extras );
	wv.show('slide-in-right',mui.os.android ? 200 : 300);
	return wv;
}
/**
 *获取页面高度,调用了  plus的api,因此需要在 plusready 之后调用 
 * add by wangsh 20161012
 */
function getDocumentHeight(){
	var domTruHright;
	if(plus.os.name == 'Android'){
		var domTruHright = plus.android.invoke(plus.android.currentWebview(),'getHeight');
		var bili = (plus.screen.resolutionWidth*plus.screen.scale)/document.body.clientWidth;
		//console.log('screenHeigth: '+domTruHright +"</br> 比例 :"+plus.screen.scale);
		return domTruHright / bili;
	}else{
		return plus.screen.resolutionHeight;
	}
}



function galleryImg(callback) { 
    plus.gallery.pick(function(a) {
    //	var HEADname = 'head'+Math.floor(100000000*Math.random())+'.png';
    	var HEADname = 'head.png';
        plus.io.resolveLocalFileSystemURL(a, function(entry) { 
            plus.io.resolveLocalFileSystemURL("_downloads/", function(root) { 
                root.getFile("head.png", {}, function(file) { 
                    //文件已存在 
                    file.remove(function() { 
                        console.log("file remove success"); 
                        entry.copyTo(root, HEADname, function(e) { 
                                var e = e.fullPath + "?version=" + new Date().getTime(); 
                                uploadHead(e,function(data,dir){
					            	callback(data,dir);
					            }); /*上传图片*/ 
                                //变更大图预览的src 
                                //目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现 
                            }, 
                            function(e) { 
                                console.log('copy image fail:' + e.message); 
                            }); 
                    }, function() { 
                        console.log("delete image fail:" + e.message); 
                    }); 
                }, function() { 
                    //文件不存在 
                    entry.copyTo(root, HEADname, function(e) { 
                            var path = e.fullPath + "?version=" + new Date().getTime(); 
                            uploadHead(path,function(data,dir){
				            	callback(data,dir); 
				            }); /*上传图片*/
                        }, 
                        function(e) { 
                            console.log('copy image fail:' + e.message); 
                        }); 
                }); 
            }, function(e) { 
                console.log("get _www folder fail"); 
            }) 
        }, function(e) { 
            console.log("读取拍照文件错误：" + e.message); 
        }); 
    }, function(a) {}, { 
        filter: "image" 
    }) 
}; 
//拍照 
function getImage(callback) { 
	//var HEADname = 'head'+Math.floor(100000000*Math.random())+'.png';
	var HEADname = 'head.png';
    var c = plus.camera.getCamera(); 
    c.captureImage(function(a) {
    	 /*上传图片*/
        plus.io.resolveLocalFileSystemURL(a, function(entry) {
        	 plus.io.resolveLocalFileSystemURL("_downloads/", function(root){
        	 	 root.getFile("head.png", {}, 
        	 	 //存在旧文件
        	 	 function(file){
        	 	 	file.remove(function(){ 
                        entry.copyTo(root, HEADname, function(e) {
                        		var e = e.fullPath + "?version=" + new Date().getTime();
                                uploadHead(e,function(data,dir){
					            	callback(data,dir);
					            }); 
                           }, function(e) { 
                                console.log('copy image fail:' + e.message); 
                            }); 
        	 	 	})
        	 	 },function(){
                    //文件不存在 
                    entry.copyTo(root, HEADname, function(e) { 
                            var path = e.fullPath + "?version=" + new Date().getTime();
                            uploadHead(path,function(data,dir){
				            	callback(data,dir); 
				            }); /*上传图片*/
                        }, 
                        function(e) { 
                            console.log('copy image fail:' + e.message); 
                        }); 
        	 	 })
        	 },function(e){
        	 	
        	 })
        }, function(es) { 
            mui.toast('获取照片失败');
        }); 
    }, function(s) { 
        console.log("error" + s); 
    }, { 
        filename: "_downloads/head"
    }) 
} 
function uploadHead(imgPath,callback) {
	callback(null,imgPath);
	return;
    var image = new Image(); 
    image.src = imgPath; 
    image.onload = function() { 
   		var imgData = getBase64Image(image);
   		callback(imgData,imgPath);
    } 
} 
  //将图片压缩转成base64 
function getBase64Image(img) { 
    var canvas = document.createElement("canvas"); 
    var width = img.width; 
    var height = img.height; 
    // calculate the width and height, constraining the proportions 
    if (width > height) { 
        if (width > 300) { 
            height = Math.round(height *= 300 / width); 
            width = 300; 
        } 
    } else { 
        if (height > 300) { 
            width = Math.round(width *= 300 / height); 
            height = 300; 
        } 
    } 
    canvas.width = width;   /*设置新的图片的宽度*/ 
    canvas.height = height; /*设置新的图片的长度*/ 
    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(img, 0, 0, width, height); /*绘图*/ 
    var dataURL = canvas.toDataURL("image/png", 0.8); 
    return dataURL.replace("data:image/png;base64,", ""); 
}
//根据url name 下载
function appappCreateDownloadTask(url,name,callback) {
	var dtask = plus.downloader.createDownload(url, {filename:name}, function(d, status) {
		if(status == 200) {
			var path = plus.io.convertLocalFileSystemURL(d.filename);
//						console.log("~~~~~"+d.filename);
//						console.log("~~~~~"+path);
			localStorage.setItem(url, path);
			callback();
		} else {
		}
	});
	dtask.start();
}
//加载头像
function showHead(src,type){
	var img = document.createElement("img");
		img.setAttribute('id','pic');
		if(!type){
			img.style.height = '100px';
			img.style.weight = '100px';
		}
		img.setAttribute('src',src );	
		document.getElementById('headImg').innerHTML = '';
		document.getElementById('headImg').appendChild(img);
}
//获取头像
function gethead(headPath,headDir){
	//头像下载
	var headurl = utils.HOST+headPath;
	var headurlSave = localStorage.getItem('$headLocalPath');
	var headLocalPath = '_downloads/head.png';
	if(headurl && (!headurlSave || headurl != headurlSave)){//存在头像,本地头像不存在 开始下载
		appCreateDownloadTask(headurl,headLocalPath,function(){
			showHead(plus.io.convertLocalFileSystemURL(headLocalPath));
			//存
			localStorage.setItem('$headLocalPath',headurl);
			localStorage.setItem('headDir', plus.io.convertLocalFileSystemURL(headLocalPath));
		});
	}else{
		plus.io.resolveLocalFileSystemURL(headLocalPath,function(entry){//文件存在跳过
			if(headDir){
				showHead(headDir);
			}else{
				showHead(plus.io.convertLocalFileSystemURL(headLocalPath));
			}
		},function(){//文件不存在重新下载
			appCreateDownloadTask(headurl,headLocalPath,function(){
				//存
				localStorage.setItem('$headLocalPath',headurl);
				localStorage.setItem('headDir', plus.io.convertLocalFileSystemURL(headLocalPath));
				
				showHead(plus.io.convertLocalFileSystemURL(headLocalPath));
			});
		})
	}
}

function createState(user, callback) {
	var state = getState();
	state.userId = user.oid;
	state.account = user.userLogin ? user.userLogin : user.lxrPhone;//兼容写法
	state.phone = user.lxrPhone;
	state.idCard = user.lxrCardno;
	//state.profession = user.profession;
	state.headerImg = user.userImg;
	state.sex = user.lxrSex;
	state.hasAttest = 1;
	state.userName = user.lxrName;
	state.userAddress = user.address;
	state.userType = user.userType;
	state.idVerifyStatus = user.idVerifyStatus;
	state.windowHandleStatus = user.windowHandleStatus;
	
	/*if(state.userType == '1'){
		state.companyName = user.companyName;
		state.companyCertType = user.companyCertType;//0 统一社会信用代码
		state.companyCardno = user.companyCardno;
		state.legalPeopleName = user.legalPeopleName;
		state.legalPeopleCardno = user.legalPeopleCardno;
	}*/
	
	//state.headPath = user.headPath;
	//state.token = user.token;
	setState(state);
	return callback();
}

//判断用户是否已实名认证
function checkUserVerifyStatus(user){
    var s = user.idVerifyStatus;
    var w = user.windowHandleStatus;//窗口实名认证状态
    var userType = user.userType;
    //先判断是否窗口实名认证
	if(w && ('-1' == w || '0' == w)) {
          return true;
	}else if(userType && userType == '0' && s && s.indexOf(1) >=0 && s.indexOf(2) >=0 && s.indexOf(3) >=0){
		//只有个人用户有多重实名认证方式
		return true;
	}
	return false;
}

/**
 * 获取当前状态
 **/
function getState() {
	var stateText = localStorage.getItem(SYS_PARAM.KEY_LOGIN_INFO) || "{}";
	return JSON.parse(stateText);
};

/**
 * 设置当前状态
 **/
function setState(state) {
	state = state || {};
	localStorage.setItem(SYS_PARAM.KEY_LOGIN_INFO, JSON.stringify(state));
};

/**
 * 移除登录状态
 */
function removeState(){
	localStorage.removeItem(SYS_PARAM.KEY_LOGIN_INFO);
}
/**
 * @param {Object} type 类型
 * @param {Object} phoneNum
 * @param {Object} callBack
 */
function sendSMS(type,phoneNum,callBack){
	var url = "appCommon/appSendSMSCode.do";
	utils.ajax(url,function(data){
		data = JSON.parse(data);
		if(data.autoShow || data.state == "1"){
			callBack?callBack(data.code,data.autoShow):'';
		}else{
			mui.toast(data.msg?data.msg:"获取短信验证码失败")			
		}
	},jsonToParams({type:type,phoneNum:phoneNum}),{showWait:true})
}
//----------------------------------------

function isAndroid(){
	var sysinfo_str = localStorage.getItem(SYS_PARAM.KEY_SYS_INFO);
	var sysinfo = JSON.parse(sysinfo_str);
	return sysinfo.name == 'Android';
}

/**
 * 获取所有站点信息
 */
function getAllSitesInfo(){
	var url = "appWebSite/queryWebSites.do";
	//获取所有站点信息
	utils.ajax(url,function(data){
		var datas = JSON.parse(data);
		if(datas && datas.state == 1){
			localStorage.setItem(SYS_PARAM.KEY_SITES_LIST,data);
		}
	});
}
